package org.example.easybuy.service.impl;

import com.antherd.smcrypto.sm3.Sm3;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.example.easybuy.dao.UserDao;
import org.example.easybuy.entity.User;
import org.example.easybuy.exceptions.NameAndPasswordException;
import org.example.easybuy.service.LoginService;
import org.example.easybuy.util.CustomResult;
import org.example.easybuy.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public User selectUserByLoginName(String loginName) {
        return userDao.selectUserByLoginName(loginName);
    }

    @Override
    public Map<String, Object> login(User user){
        User loginUser=userDao.selectUserByLoginName(user.getLoginName());
        Map<String,Object> map=new HashMap<>();
        if(loginUser==null)
        {
            //用戶不存在
           throw new NameAndPasswordException("no");
        }else{
            String pass= Sm3.sm3(user.getPassword());
            if(pass.equals(loginUser.getPassword()))
            {
                String token= JwtUtil.createToken(loginUser.getLoginName());
                //将用户存入redis,30分钟
                stringRedisTemplate.opsForValue().set(loginUser.getLoginName(),token,30, TimeUnit.MINUTES);
                map.put("token", token);
            }else{
                //密码错误
                throw new NameAndPasswordException("inCorrect");
            }
        }
        return map;
    }
}
